﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace DataAccessor
{
    /// <summary>
    /// Mapping文件解析类
    /// </summary>
    public class MappingParser
    {
        #region 成员变量
        /// <summary>
        /// Mapping配置文件
        /// </summary>
        private readonly XmlDocument _mappingXML;
        /// <summary>
        /// Mapping配置的所有类型
        /// </summary>
        private MappingType[] _mappingTypeCollection;
        #endregion

        /// <summary>
        /// 创建MappingParser的一个实例
        /// </summary>
        public MappingParser(XmlDocument tsqlXML)
        {
            _mappingXML = tsqlXML;
            Parser();
        }

        /// <summary>
        /// 从指定的Mapping配置文件创建MappingParser的一个实例
        /// </summary>
        public MappingParser(string mappingFilePath)
        {
            _mappingXML = new XmlDocument();
            LoadMappingXML(mappingFilePath);
            Parser();
        }

        /// <summary>
        /// 加载XML文件到XMLDocument
        /// </summary>
        /// <param name="mappingFilePath"></param>
        private void LoadMappingXML(string mappingFilePath)
        {
            if (string.IsNullOrEmpty(mappingFilePath))
            {
                throw new NullReferenceException("无法从空的Mapping配置文件路径解析文件。");
            }

            if (!File.Exists(mappingFilePath))
            {
                throw new FileNotFoundException("没有找到文件：" + mappingFilePath);
            }
            _mappingXML.Load(mappingFilePath);
        }

        /// <summary>
        /// 解析XML文件
        /// </summary>
        private void Parser()
        {
            var bytes = UnicodeEncoding.UTF8.GetBytes(_mappingXML.InnerXml);
            var stream = new MemoryStream(bytes);

            var serializer = new XmlSerializer(typeof(Mapping));
            Mapping mapping = null;
            try
            {
                mapping = serializer.Deserialize(stream) as Mapping;
            }
            catch (Exception ex)
            {
                throw new XmlException("反序列化Mapping.xml失败", ex);
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
            _mappingTypeCollection = mapping.Type;
        }

        /// <summary>
        /// 获取Mapping配置的所有类型
        /// </summary>
        public MappingType[] MappingType
        {
            get { return _mappingTypeCollection; }
        }
    }
}
